package com.butterfly.wx.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.butterfly.common.exception.BaseExcetion;
import com.butterfly.wx.model.WeChatSessionModel;
import com.butterfly.wx.service.WxApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@Service
@Slf4j
public class WxApiImpl implements WxApi {
    @Value("${wechat.appId}")
    private String appId;
    @Value("${wechat.secret}")
    private String appsecret;
    @Resource
    private RestTemplate restTemplate;

    @Override
    public WeChatSessionModel getWeChatModel(String code) {
        if (StrUtil.isBlankIfStr(code)) {
            throw new BaseExcetion();
        }
        //微信服务器的接口路径
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + appsecret + "&js_code=" + code + "&grant_type=authorization_code";
        //进行网络请求,访问微信服务器接口
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type", "application/json");
            HttpEntity<String> body = new HttpEntity<>(headers);
            ResponseEntity<String> responseBody = restTemplate.exchange(url, HttpMethod.GET, body,
                    new ParameterizedTypeReference<String>() {
                    });
            log.info("getWeChatModel  response:{}.", responseBody.getBody());
            if (responseBody.getBody() != null) {
                return JSONUtil.toBean(responseBody.getBody() ,WeChatSessionModel.class);
            }
            throw new BaseExcetion();
        } catch (Exception e) {
            log.error("getWeChatModel exception:{}.", e.getMessage(), e);
            return null;
        }
    }
}
